/**
  ******************************************************************************
  * @author Chris
  * @since 2023/2/23 23:36
  *
  * @file     key.c
  * @brief    The project will ...
  *
  * @note     ...
  *
  * @warning  Do not to ...
  ******************************************************************************
  * Change Logs:
  *   Date           Author       Notes
  *   2023/2/23     Chris        the first version
  *
  ******************************************************************************
  */

#include "key.h"
#include "alientek_delay.h"

void KEY_Init(void)
{
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();

  GPIO_InitTypeDef GPIO_Init;

  GPIO_Init.Pin = GPIO_PIN_5;
  GPIO_Init.Mode = GPIO_MODE_INPUT;
  GPIO_Init.Pull = GPIO_PULLUP;
  GPIO_Init.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(GPIOC, &GPIO_Init);

  GPIO_Init.Pin = GPIO_PIN_15;
  HAL_GPIO_Init(GPIOA, &GPIO_Init);

  GPIO_Init.Pin = GPIO_PIN_0;
  GPIO_Init.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOA, &GPIO_Init);
}

u8 KEY_Scan(u8 mode)
{
  static u8 key_up = 1;

  if (mode == 1) key_up = 1;

  if (key_up && (KEY0 == 0 || KEY1 == 0 || WK_UP == 1))
  {
    delay_ms(10);
    key_up = 0;
    if (KEY0 == 0) return KEY0_PRESS;
    else if (KEY1 == 0) return KEY1_PRESS;
    else if (WK_UP == 1) return WKUP_PRESS;
  } else if (KEY0 == 1 && KEY1 == 1 && WK_UP == 0)
  {
    key_up = 1;
  }
  return 0;
}